//
//  Profile.m
//  Gradekeeper0.2
//
//  Created by Libo Zhou on 10/22/09.
//  Copyright 2009 i5. All rights reserved.
//
//  Reference: http://www.stanford.edu/class/cs193p/downloads/07-NavigationTabBarControllers.pdf
//  Reference: http://blogs.oreilly.com/iphone/2009/01/defining-legal-input-character.html


#import "ProfileController.h"
#import "fileIO.h"
#import "ProfileTableViewController.h"
#define LEGAL	@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

/*
Profile Controller will provide the necessary view and function for profile creation.
User creates a profile by entering a legal username (3~20 letter/number), noncase sensitive.
Alert box will appear if user tries to create a profile with username less than 3 characters long,
or if a profile with the same username already exists.
The user can choose to cancel profile creation, where an alert box will pop up to ask for cancel confirmation. 
*/

@implementation ProfileController


- (void)viewDidLoad {
	//Create a cancel button that lets the user cancel profile creation
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" 
								  style:UIBarButtonItemStyleBordered 
								  target:self 
								  action:@selector(cancelCreate:)]; 
	self.navigationItem.leftBarButtonItem = cancelButton; 
	[cancelButton release]; 
	self.title = [NSString stringWithFormat:@"Profile Creation"];
								  
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[inputName release];
    [super dealloc];
}

- (void)cancelCreate:(id)sender {
	
	//If user confirms cancellation, current view will be popped and return to profile manager list (ProfileTableViewController)
	UIAlertView *alert = [[UIAlertView alloc] 
						  initWithTitle:@"Cancel Confirmation" 
						  message:@"Are you sure you would like to cancel profile creation?" 
						  delegate:self
						  cancelButtonTitle:@"Yes" 
						  otherButtonTitles:nil]; 
	[alert addButtonWithTitle:@"No"];
    [alert show];
	
	[alert release];
	
} //cancelCreate

- (IBAction) btnClickMe_Clicked: (id) sender{
	NSString *myName = inputName.text;
	
	//Checks if username is at least 3 characters long, or if the profile already exists.
	//If a profile is created, the user will be alerted
	if ([myName length] < 3){
	
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid Username" 
							  message:@"Please input a username of at least 3 characters long." 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		
	} else if ([self profileExist:myName]){
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid Username" 
							  message:@"The name you have entered has already been taken. Please choose another name." 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		
	} else {
		[self writeToTextFile:self];
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Profile Creation" 
							  message:@"Profile Successfully Created" 
							  delegate:self
							  cancelButtonTitle:@"Ok" 
							  otherButtonTitles:nil]; 
		[alert show];
		[alert release];
	}
} //btnClickMe_Clicked


//If the alert is due to invalid username, do nothing
//Otherwise, the alert comes from cancellation request
//If cancellation is confirmed, pop to root view controller
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"Invalid Username"]){
	} else { 
		if (buttonIndex == 0) {
			[[self navigationController] popToRootViewControllerAnimated:YES];
		}
    }
} //alertView

//Takes the username entered and addeds it to profileManager.txt
//and creates a textfile with the same name as the entered username.
-(IBAction) writeToTextFile:(id)sender{
	NSString *myName = inputName.text;

	[fileIO appendToFile:@"profileManager" :myName];
	
	[fileIO writeToFile:myName:@""];	
		
} //writeToTextFile

//Checks if a profile with the same username exists by comparing the entered username to names in profileManager.txt
- (BOOL) profileExist: (NSString *) desiredName{
	NSString *profileManager = @"profileManager";
	NSString *tempProfileList = nil;

	tempProfileList = [[NSString alloc] initWithFormat:@"%@", [fileIO readFromFile:profileManager]];
	
	NSArray *tempArray = [tempProfileList componentsSeparatedByString: @":"];
	for (int y = 1; y < [tempArray count]; y ++){
	
		if ([[tempArray objectAtIndex:y] caseInsensitiveCompare: desiredName] == NSOrderedSame){
	
			return YES;
		} 			
	};	
	
	return NO;
} //profileExist


// allow only legal input (less than 20 chars, numbers/letters)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	NSInteger insertDelta = string.length - range.length;
	
	if (textField.text.length + insertDelta > 20)
	{
		return NO; // the new string would be longer than MAX_LENGTH
	}
	else {
		NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
		NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
		
		return [string isEqualToString:filtered];
	}
} //textField

//Hides the keyboard after finishing text input (clicking done)
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	if (textField == inputName) {
		[inputName resignFirstResponder];
	}
	return YES;
} //textFieldShouldReturn

@end
